package reflect;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * 通过暴力反射调用类的私有方法
 */
public class ReflectDemo7 {
    public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, InstantiationException, IllegalAccessException, InvocationTargetException {
        //不能访问私有方法
        Class cls = Class.forName("reflect.Person");
        Constructor c = cls.getConstructor();
        Object obj = cls.newInstance();

        //  Method method = cls.getMethod("hehe");  //运行时异常，因为getMethod()只能获取公开方法
        Method method = cls.getDeclaredMethod("hehe ");
        method.setAccessible(true);  //强制打开访问权限
        method.invoke(obj);
        method.setAccessible(false);  //关闭访问权限
    }
}
